package com.jastar.android.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.Objects;

public class Utils {

    /** 获取活动页逻辑尺寸(建议使用) */
    public static Point getActivityDisplaySize(Activity activity) {
        DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
        return new Point(metrics.widthPixels, metrics.heightPixels);
    }

    /** 获取屏幕物理尺寸(不建议使用) */
    public static Point getWindowDisplaySize(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }

    public static Rect scale(Rect rect, float ratio) {
        int w = rect.right - rect.left, h = rect.bottom - rect.top;
        int l = (int) (rect.left + w * (1 - ratio) / 2);
        int t = (int) (rect.top + h * (1 - ratio) / 2);
        int r = (int) (rect.right - w * (1 - ratio) / 2);
        int b = (int) (rect.bottom - h * (1 - ratio) / 2);
        return new Rect(l, t, r, b);
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Log.e(Utils.class.getSimpleName(), Objects.requireNonNull(e.getMessage()));
        }
    }

    public static int dip2px(Context context, float dpValue) {
        //获取当前手机的像素密度(1个dp对应几个px)
        float scale = context.getResources().getDisplayMetrics().density;
        //四舍五入取整
        return (int) (dpValue * scale + 0.5f);
    }

    /** 隐藏输入法 */
    public static void hideOneInputMethod(Activity act, View v) {
        //从系统服务中获取输入法管理器
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        //关闭屏幕上的输入法软键盘
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

}
